package com.powernode.queryops;

import com.powernode.commons.util.ReleaseResourceUtils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @Author Arrebol
 * @Date 2024/8/1 14:13
 * @Project jdbc
 * @Description： 获取结果集元数据信息————ResultSetMetaDate
 */
public class JdbcTest3 {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            stmt = conn.createStatement();
            String sql1 = "select * from t_product";
            rs = stmt.executeQuery(sql1);
            //通过结果集获取结果集元数据
            //通过结果集元数据可以获取列的信息————列名、数据类型、长度...
            ResultSetMetaData metaData = rs.getMetaData();
            //获取列数量
            int columnCount = metaData.getColumnCount();
            System.out.println("共"+columnCount+"列");
            //遍历每一列
            for (int i = 1; i <= columnCount; i++) {
                //i是列的下标，jdbc中下标从1开始
                //获取列名
                String columnName = metaData.getColumnName(i);
                System.out.println("第"+i+"列的列名为："+columnName);
                String columnTypeName = metaData.getColumnTypeName(i);
                System.out.println("第"+i+"列的列类型名为："+columnTypeName);
                //获取列的长度
                int columnDisplaySize = metaData.getColumnDisplaySize(i);
                System.out.println("第"+i+"列的长度为："+columnDisplaySize);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReleaseResourceUtils.release(rs,stmt,conn);
        }
    }
}
